<template>
  <div class="senseless-config">
    <div class="operation-bar">
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增配置</el-button>
      <el-button icon="el-icon-refresh" @click="refreshList">刷新</el-button>
    </div>

    <el-table v-loading="loading" :data="configList" border stripe highlight-current-row>
      <el-table-column prop="lotId" label="停车场" width="180">
        <template slot-scope="scope">
          <el-select v-model="scope.row.lotId" placeholder="请选择停车场" disabled>
            <el-option v-for="item in parkingLots" :key="item.lotId" :label="item.lotName" :value="item.lotId">
            </el-option>
          </el-select>
        </template>
      </el-table-column>

      <el-table-column prop="payType" label="支付类型" width="120">
        <template slot-scope="scope">
          <el-tag :type="scope.row.payType === '1' ? 'success' : 'primary'">
            {{ scope.row.payType === '1' ? '微信支付' : '支付宝' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="merchantId" label="商户号" width="180" show-overflow-tooltip></el-table-column>
      <el-table-column prop="merchantName" label="商户名称" width="180" show-overflow-tooltip></el-table-column>
      <el-table-column prop="appId" label="应用ID" width="180" show-overflow-tooltip></el-table-column>
      <el-table-column prop="merchantKey" label="商户密钥" width="180">
        <template slot-scope="scope">
          <span>{{ hidePassword(scope.row.merchantKey) }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="priority" label="优先级" width="100" align="center">
        <template slot-scope="scope">
          <el-tag size="medium">{{ scope.row.priority }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="status" label="状态" width="100" align="center">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" active-value="0" inactive-value="1"
            @change="handleStatusChange(scope.row)" active-text="启用" inactive-text="停用">
          </el-switch>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="150" fixed="right">
        <template slot-scope="scope">
          <el-button type="text" icon="el-icon-edit" @click="handleEdit(scope.row)">编辑</el-button>
          <el-popconfirm title="确认删除该配置吗？" @confirm="handleDelete(scope.row.configId)">
            <el-button slot="reference" type="text" icon="el-icon-delete" class="danger-text">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px" :close-on-click-modal="false"
      @closed="resetForm">
      <el-form :model="formData" :rules="rules" ref="configForm" label-width="100px" :validate-on-rule-change="false">
        <el-form-item label="停车场" prop="lotId">
          <el-select v-model="formData.lotId" placeholder="请选择停车场" filterable>
            <el-option v-for="item in parkingLots" :key="item.lotId" :label="item.lotName" :value="item.lotId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="支付类型" prop="payType">
          <el-radio-group v-model="formData.payType">
            <el-radio label="1">微信支付</el-radio>
            <el-radio label="2">支付宝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="商户号" prop="merchantId">
          <el-input v-model="formData.merchantId" maxlength="50" show-word-limit>
          </el-input>
        </el-form-item>
        <el-form-item label="商户名称" prop="merchantName">
          <el-input v-model="formData.merchantName" maxlength="100" show-word-limit>
          </el-input>
        </el-form-item>
        <el-form-item label="应用ID" prop="appId">
          <el-input v-model="formData.appId" maxlength="50" show-word-limit>
          </el-input>
        </el-form-item>
        <el-form-item label="商户密钥" prop="merchantKey">
          <el-input v-model="formData.merchantKey" type="password" show-password maxlength="100">
          </el-input>
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-input-number v-model="formData.priority" :min="1" :max="99" controls-position="right">
          </el-input-number>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="formData.status" active-value="0" inactive-value="1" active-text="启用" inactive-text="停用">
          </el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPaymentConfig,
  addPaymentConfig,
  updatePaymentConfig,
  deletePaymentConfig
} from '@/api/parkinglotmanagement/paymentConfig'
import { listLot } from '@/api/parkinglotmanagement/parking'

export default {
  name: 'SenselessConfiguration',
  data() {
    return {
      loading: false,
      submitLoading: false,
      configList: [],
      parkingLots: [],
      dialogVisible: false,
      dialogTitle: '',
      formData: this.getInitialFormData(),
      rules: {
        lotId: [
          { required: true, message: '请选择停车场', trigger: 'change' }
        ],
        payType: [
          { required: true, message: '请选择支付类型', trigger: 'change' }
        ],
        merchantId: [
          { required: true, message: '请输入商户号', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        merchantName: [
          { required: true, message: '请输入商户名称', trigger: 'blur' },
          { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
        ],
        appId: [
          { required: true, message: '请输入应用ID', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        merchantKey: [
          { required: true, message: '请输入商户密钥', trigger: 'blur' },
          { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
        ],
        priority: [
          { required: true, message: '请设置优先级', trigger: 'blur' },
          { type: 'number', message: '优先级必须为数字', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getConfigList()
    this.getParkingLots()
  },
  methods: {
    getInitialFormData() {
      return {
        configId: '',
        lotId: '',
        payType: '1',
        merchantId: '',
        merchantName: '',
        appId: '',
        merchantKey: '',
        priority: 1,
        status: '0'
      }
    },
    async refreshList() {
      await this.getConfigList()
      this.$message.success('刷新成功')
    },
    async getConfigList() {
      this.loading = true
      try {
        const response = await listPaymentConfig()
        this.configList = Array.isArray(response.data.records) ? response.data.records : []
      } catch (error) {
        this.$message.error('获取配置列表失败')
        this.configList = []
      } finally {
        this.loading = false
      }
    },
    async getParkingLots() {
      try {
        const response = await listLot()
        this.parkingLots = response.data || []
      } catch (error) {
        console.error('获取停车场列表失败:', error)
        this.$message.error('获取停车场列表失败')
        this.parkingLots = []
      }
    },
    hidePassword(str) {
      if (!str) return ''
      return '*'.repeat(str.length)
    },
    handleAdd() {
      this.dialogTitle = '新增配置'
      this.dialogVisible = true
      this.formData = this.getInitialFormData()
    },
    handleEdit(row) {
      this.dialogTitle = '编辑配置'
      this.dialogVisible = true
      this.formData = JSON.parse(JSON.stringify({
        configId: row.configId,
        lotId: row.lotId,
        payType: row.payType,
        merchantId: row.merchantId,
        merchantName: row.merchantName,
        appId: row.appId,
        merchantKey: row.merchantKey,
        priority: row.priority,
        status: row.status
      }))
    },
    async handleStatusChange(row) {
      try {
        await updatePaymentConfig(row)
        this.$message.success('状态更新成功')
      } catch (error) {
        this.$message.error('状态更新失败')
        row.status = row.status === '0' ? '1' : '0' // 恢复状态
      }
    },
    async handleDelete(configId) {
      try {
        await deletePaymentConfig({ configId: configId })
        this.$message.success('删除成功')
        await this.getConfigList()
      } catch (error) {
        console.error('删除失败:', error)
        this.$message.error('删除失败')
      }
    },
    resetForm() {
      this.$refs.configForm?.resetFields()
      this.formData = this.getInitialFormData()
    },
    handleSubmit() {
      this.$refs.configForm.validate(async (valid) => {
        if (valid) {
          this.submitLoading = true
          try {
            const isAdd = this.dialogTitle === '新增配置'
            await (isAdd ? addPaymentConfig(this.formData) : updatePaymentConfig(this.formData))
            this.$message.success(isAdd ? '新增成功' : '更新成功')
            this.dialogVisible = false
            this.getConfigList()
          } catch (error) {
            this.$message.error(isAdd ? '新增失败' : '更新失败')
          } finally {
            this.submitLoading = false
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.senseless-config {
  padding: 20px;

  .operation-bar {
    margin-bottom: 20px;
    display: flex;
    gap: 10px;
  }

  .danger-text {
    color: #F56C6C;
    margin-left: 10px;

    &:hover {
      color: #f78989;
    }
  }

  ::v-deep .el-table {
    margin-bottom: 20px;
  }
}
</style>
